/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.coupon.handler;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ykht.proj.admin.api.entity.SysSocialDetails;
import com.ykht.proj.admin.api.feign.RemoteSysSocialDetailsService;
import com.ykht.proj.common.core.constant.CacheConstants;
import com.ykht.proj.common.core.constant.CommonConstants;
import com.ykht.proj.common.core.constant.SecurityConstants;
import com.ykht.proj.common.core.constant.enums.LoginTypeEnum;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.coupon.entity.CnPerson;
import com.ykht.proj.coupon.entity.FxPersonAccount;
import com.ykht.proj.coupon.mapper.CnPersonMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author proj
 * @date 2019年11月02日
 * <p>
 * 微信小程序
 */
@Slf4j
@Component("MINI_C")
@RequiredArgsConstructor
public class MiniCAppLoginHandler extends AbstractLoginHandler {

	private final CnPersonMapper cnPersonMapper;
	private final RedisTemplate redisTemplate;
	private final RemoteSysSocialDetailsService remoteSysSocialDetailsService;


	/**
	 * 小程序登录传入code
	 * <p>
	 * 通过code 调用qq 获取唯一标识
	 * @param code
	 * @return
	 */
	@Override
	public String identify(String code) {
//		SysSocialDetails condition = new SysSocialDetails();
//		condition.setType(LoginTypeEnum.MINI_APP.getType());
//		condition.setType("MINI_C");
		R<SysSocialDetails> r = remoteSysSocialDetailsService.getOne(LoginTypeEnum.MINI_C.getType(),SecurityConstants.FROM_IN);
		SysSocialDetails social = r.getData();
		System.out.println(JSONUtil.toJsonStr(social));

		//暂时这么处理，后续改成调用服务获取
//		String url = String.format(SecurityConstants.MINI_APP_AUTHORIZATION_CODE_URL,"wx66d31936b1685d4d",
//				"ece7f92e5b0f127dc062132ac52b3050", code);
		String url = String.format(SecurityConstants.MINI_APP_AUTHORIZATION_CODE_URL,social.getAppId(), social.getAppSecret(), code);
		String result = HttpUtil.get(url);
		log.debug("微信小程序响应报文:{}", result);

		Object openId = JSONUtil.parseObj(result).get("openid");
		Object sessionKey = JSONUtil.parseObj(result).get("session_key");
//		openId="o7xw-5NxoLCQgYCb3eLZkyKSzBU4";
		//测试
//		openId="o7xw-5Jds0rhAgr_MvQVTldA7NOc";
		//彩云
//		openId="o7xw-5KHFyOEBNTiM0g2UtGgWDDw";
		if(null != openId && null != sessionKey){
			redisTemplate.opsForValue().set(CacheConstants.USER_SEEESINKEY_BY_OPENID+openId.toString(), sessionKey.toString());
		}
		log.info("->openid:{}",openId);
		return String.valueOf(openId);
	}

	/**
	 * openId 获取用户信息
	 * @param openId
	 * @return
	 */
	@Override
	public Object info(String openId) {
		if (StringUtil.isEmpty(openId)||"null".equals(openId)) return null;
		CnPerson person = cnPersonMapper.selectOne(Wrappers.lambdaQuery(CnPerson.class).eq(CnPerson::getOpenId,openId));
		if (null != person) {
			person.setLoginTime(LocalDateTime.now());
			person.updateById();
			checkAndcreateAccount(person);
			return person;
		}else {
			log.info("->首次登陆，创建用户openid：{}", openId);
			person = createPerson(openId);
			createAccount(person);
			return person;
		}
	}

	/**
	 * 检查并创建账户
	 * @param person
	 * @return
	 */
	private FxPersonAccount checkAndcreateAccount(CnPerson person){
		FxPersonAccount account = new FxPersonAccount().selectOne(Wrappers.lambdaQuery(FxPersonAccount.class).eq(FxPersonAccount::getPersonId,person.getId()));
		if (account ==null){
			account = createAccount(person);
		}
		return account;
	}

	/**
	 * 创建账户
	 * @param person
	 * @return
	 */
	private FxPersonAccount createAccount(CnPerson person){
		FxPersonAccount account = new FxPersonAccount();
		account.setAccount(String.format(CommonConstants.ACCONCE_FORMAT,person.getId()));
		account.setPersonId(person.getId());
		account.setType(0);
		account.setCreateUser(person.getId());
		account.setCreateTime(LocalDateTime.now());
		account.insert();
		return account;
	}
	/**
	 * 创建用户
	 * @param openId
	 * @return
	 */
	private CnPerson createPerson(String openId){
		CnPerson temp = new CnPerson();
		temp.setOpenId(openId);
		temp.setStatus(0);
		temp.setCreateTime(LocalDateTime.now());
		temp.setCreateUser(temp.getId());
		temp.setLoginType(0);//微信小程序
		temp.setLoginTime(LocalDateTime.now());
		temp.insert();
		createAccount(temp);
		return temp;
	}

}
